package com.vegetable.modules.exception;

import com.vegetable.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@Order(999999)
@RestControllerAdvice
public class RRExceptionHandler {

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RRException.class)
	public R handleRRException(RRException e){
		return R.fail(e.getCode(), e.getMessage());
	}
	
	/**
	 * 处理交易流水与付款记录匹配关系业务异常
	 */
	@ExceptionHandler(TransactionPaymentMatchException.class)
	public R handleTransactionPaymentMatchException(TransactionPaymentMatchException e){
		return R.fail(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public R handlerNoFoundException(Exception e) {
		log.error("路径不存在，请检查路径是否正确--->", e);
		return R.fail(404, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		log.error(e.getMessage(), e);
		return R.fail("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public R handleAuthorizationException(AuthorizationException e){
		log.error("没有权限，请联系管理员授权", e);
		return R.fail("没有权限，请联系管理员授权");
	}

	/**
	 * 通用异常处理
	 */
	@ExceptionHandler(Exception.class)
	public R exceptionHandler(Exception e) {
		log.error("----------------->", e);
		return R.fail(HttpStatus.SC_BAD_REQUEST,e.getMessage());
	}

	@ExceptionHandler(NullPointerException.class)
	public R errorHandler(NullPointerException ex) {
		log.error("空指针异常-------->", ex);
		return R.fail(HttpStatus.SC_BAD_REQUEST,"空指针异常！");
	}

	@ExceptionHandler(OptimisticLockingFailureException .class)
	public R errorHandler(OptimisticLockingFailureException ex) {
		log.error("乐观锁异常异常-------->", ex);
		return R.fail(HttpStatus.SC_BAD_REQUEST,"订单已被其他用户更新，请刷新后重试");
	}
}